package cn.xspace.library.util;

import com.ctnq.util.EncryptUtil;
import com.xspace.android.xafcommon.appliction.BaseApplication;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Wubj 创建于 2017/3/13 0010.
 */
public class OkHttpUtils {

    private static final String TAG = OkHttpUtils.class.getSimpleName();

    /**
     * 针对RXJava专用同步网络请求
     *
     * @param url
     * @param params
     */
    public static BaseReturnBean initHttp(String url, Map<String, Object> params) {
        final String sendJson = JSONUtil.parseMapToJson(params);
        LogUtil.i(TAG, "params>>>>" + params);
        LogUtil.i(TAG, "url>>>>" + url);
        EncryptBean encryptBean = new EncryptBean(params);
        String sendData = encryptBean.sendData(encryptBean);
        LogUtil.v(TAG, "sendData>>>" + sendData);
        MediaType JSON = MediaType.parse("application/octet-stream; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, sendData);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = BaseApplication.sOkHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = EncryptUtil.getInstance().getDecryptData(response.body().string());
                LogUtil.i(TAG, "url :" + url + "\nparams :" + sendJson + "\n返回结果 :" + result);
                BaseReturnBean bean = optBaseReturnBean(result);
                LogUtil.d("returnBean.code>>" + bean.code);
                LogUtil.d("returnBean.desc>>" + bean.desc);
                return bean;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d(TAG, "wubaojie>>>initHttp: 解密失败");
        }
        return null;
    }

    public static BaseReturnBean initHttpWithoutEncrypt(String url, Map<String, Object> params) {
        final String sendJson = JSONUtil.parseMapToJson(params);
        LogUtil.i(TAG, "params>>>>" + params);
        LogUtil.i(TAG, "url>>>>" + url);
        final String sendData = JSONUtil.parseMapToJson(params);
        if (sendData == null) {
            return null;
        }
        MediaType JSON = MediaType.parse("application/octet-stream; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, sendData);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = BaseApplication.sOkHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                LogUtil.i(TAG, "url :" + url + "\nparams :" + sendJson + "\n返回结果 :" + result);
                BaseReturnBean bean = optBaseReturnBeanOld(result);
                LogUtil.d("returnBean.code>>" + bean.code);
                LogUtil.d("returnBean.desc>>" + bean.desc);
                return bean;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d(TAG, "wubaojie>>>initHttp: 解密失败");
        }
        return null;
    }


    public static BaseReturnBean initHttp(String url, String params) {
        LogUtil.i(TAG, "params>>>>" + params);
        LogUtil.i(TAG, "url>>>>" + url);
        EncryptBean encryptBean = new EncryptBean(params);
        String sendData = encryptBean.sendData(encryptBean);
        LogUtil.v(TAG, "sendData>>>" + sendData);
        MediaType JSON = MediaType.parse("application/octet-stream; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, sendData);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = BaseApplication.sOkHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = EncryptUtil.getInstance().getDecryptData(response.body().string());
                LogUtil.i(TAG, "url :" + url + "\nparams :" + params + "\n返回结果 :" + result);
                BaseReturnBean bean = optBaseReturnBean(result);
                LogUtil.d("returnBean.code>>" + bean.code);
                LogUtil.d("returnBean.desc>>" + bean.desc);
                return bean;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d(TAG, "wubaojie>>>initHttp: 解密失败");
        }
        return null;
    }

    public static boolean isSuccess(BaseReturnBean bean) {
        return bean != null && (bean.code.endsWith(ErrorCode.SUCCESS_CODE_SUFFIX) || "0".equals(bean.code));
    }

    private static BaseReturnBean optBaseReturnBean(String result) {
        final BaseReturnBean returnBean = new BaseReturnBean();
        JSONObject dataJSon;
        try {
            JSONObject proDataJSON = new JSONObject(result);
            String proDataStr = proDataJSON.optString("pro_data");
            dataJSon = new JSONObject(proDataStr);
            returnBean.code = dataJSon.optString("code");
            returnBean.desc = dataJSon.optString("desc");
            String data = "";
            if (dataJSon.has("data")) {
                data = dataJSon.optString("data");
            } else if (dataJSon.has("msgList")) {
                data = dataJSon.optString("msgList");
            } else if (dataJSon.has("msg")) {
                data = dataJSon.optString("msg");
            }
            returnBean.data = data;
            LogUtil.d(TAG, "returnBean.data>>" + data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return returnBean;
    }

    private static BaseReturnBean optBaseReturnBeanOld(String result) {
        final BaseReturnBean returnBean = new BaseReturnBean();
        JSONObject dataJSon;
        try {
            dataJSon = new JSONObject(result);
            returnBean.code = dataJSon.optString("code");
            returnBean.desc = dataJSon.optString("desc");
            String data = "";
            if (dataJSon.has("data")) {
                data = dataJSon.optString("data");
            } else if (dataJSon.has("msgList")) {
                data = dataJSon.optString("msgList");
            } else if (dataJSon.has("msg")) {
                data = dataJSon.optString("msg");
            }
            returnBean.data = data;
            LogUtil.d(TAG, "returnBean.data>>" + data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return returnBean;
    }
}
